import ClassPathBeanDefinitionScanner from "@framework/context/ClassPathBeanDefinitionScanner";
import Path from "node:path";
import KoaBootFile from "@framework/web/KoaBootFile";
import KoaBootLogger from "@framework/web/KoaBootLogger";
import DefaultListableBeanFactory from "@framework/bean/DefaultListableBeanFactory";

/**
 * 负责处理IOC容器逻辑
 */
class ConstructBeanProvider {

    /**
     * 日志
     * @private
     */
    private logger: KoaBootLogger = KoaBootLogger.getInstance();

    /**
     * Bean构造工厂
     * @private
     */
    private beanFactory: DefaultListableBeanFactory;

    /**
     * 资源扫描器
     * @private
     */
    private definitionScanner: ClassPathBeanDefinitionScanner;

    /**
     * 扫描工作路径
     * @private
     */
    private readonly workPath:string = Path.join(KoaBootFile.getRootPath(), "src", "main", "app");

    /**
     * 构造函数
     * @param definitionScanner
     * @param beanFactory
     */
    constructor(definitionScanner: ClassPathBeanDefinitionScanner, beanFactory: DefaultListableBeanFactory) {
        this.definitionScanner = definitionScanner;
        this.beanFactory = beanFactory;
        this.registerBeanDefinition();
    }

    /**
     * 加载TS资源并且根据导出的模块注册 BeanDefinition
     */
    public registerBeanDefinition() {
        this.logger.info(`KoaBoot Application Start Up`);
        const resourceList = this.definitionScanner.readFilePath(this.workPath);
        for (const path of resourceList) {
            try {
                this.logger.debug(`Register BeanDefinition By Path: ${path}`);
                const defaultModule = require(path).default;
                if (!(defaultModule && defaultModule instanceof Function)) {
                    continue;
                }
                this.beanFactory.registerBeanDefinition({ defaultModule, path });
            } catch (e) {
                this.logger.error(e)
            }
        }
        this.logger.info(`Register BeanDefinition Ends`);
    }
}

export default ConstructBeanProvider;